<template>
    <div class="home">
        <div class="main">
            <van-swipe 
                class="my-swipe" 
                :loop="isLoop" 
                :autoplay="3000" 
                indicator-color="white" 
                :touchable="true" 
                :initial-swipe="swipeIndex" 
                @change="swipeChange"
            >
                <van-swipe-item>
                    <div class="swipe-item-1-text">{{ zupuname }}</div>
                    <van-image 
                        width="100%" 
                        height="100%" 
                        fit="cover" 
                        :src="cover" 
                    />
                </van-swipe-item>
                <van-swipe-item 
                    v-for="(item1, index1) in familyArr2" 
                    :key="index1"
                >
                    <div class="box-1">
                        <div class="box-2">
                            <template v-for="(item2, index2) in item1">
                                <div 
                                    v-if="index1 == 0 && index2 == 0" 
                                    class="box-3-header" 
                                    :key="2 + '-' + index2"
                                >
                                    {{ zupuname }}成员介绍
                                </div>
                                <div 
                                    v-if="item2.title" 
                                    class="box-3-title" 
                                    :key="3 + '-' + index2"
                                >
                                    {{ item2.title }}
                                </div>
                                <div 
                                    v-else class="box-4" 
                                    :key="4 + '-' + index2"
                                >
                                    <div class="box-4-call">{{ item2.call }}</div>
                                    <div class="box-4-name">{{ item2.cm_name }}</div>
                                    <div class="box-4-direction">{{ item2.cm_synopsis }}</div>
                                </div>
                            </template>
                        </div>
                    </div>
                </van-swipe-item>
                <van-swipe-item>
                    <div class="swipe-item-1-text">{{ zupuname }}封底</div>
                    <van-image 
                        width="100%" 
                        height="100%" 
                        fit="cover" 
                        :src="backCover" 
                    />
                </van-swipe-item>
            </van-swipe>
            <van-button @click="isLoop = !isLoop">开始/暂停滚动</van-button>
        </div>
        <div class="mbutton">
            <div class="mbutton-box">
                <van-button 
                    type="danger" 
                    style="flex: 1;height: 100%;" 
                    @click="del"
                >
                    删除
                </van-button>
                <van-button 
                    type="primary" 
                    style="flex: 2;height: 100%;" 
                    @click="edit"
                >
                    编辑
                </van-button>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
    import { delClanInfoApi, getClanMemberByIdApi, getClanByIdApi } from '@/apis'
    import { showDialog, showConfirmDialog, showLoadingToast, closeToast, showSuccessToast, showFailToast, showToast } from 'vant'
    import { markRaw, reactive, ref, toRaw, onMounted, onBeforeMount, readonly, onBeforeUnmount } from 'vue'
    import type { Ref, Raw } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    const route = useRoute()
    const router = useRouter()

    const cover: Ref<string> = ref('')
    const backCover: Ref<string> = ref('')
    const zupuname: Ref<string> = ref('')
    const familyArr1: Ref<any[]> = ref([])
    const familyArr2: Ref<any[]> = ref([])
    const familyData: Ref<any[]> = ref([])
    const swipeIndex: Ref<number> = ref(0)
    const isLoop: Ref<boolean> = ref(false)
    const ranking: Ref<any[]> = ref(['长', '次', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九', '二十'])
    const num: Ref<any[]> = ref(['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九', '二十'])
    
    onBeforeMount(() => {
        getClanByIdApi({
            company: '连云港人文纪念园智慧陵园管理系统',
            dw: '连云港人文纪念园',
            sId: route.query.cm_mainid
        }).then(res => {
            cover.value = res.data[0].c_cover
            backCover.value = res.data[0].c_back_cover
            zupuname.value = res.data[0].c_name + '氏族谱'
        }).catch(err => {
            showDialog({
                title: '提示',
                message: '网络异常，请稍后重试！',
            }).then(() => {
            });
        })
        getClanMemberByIdApi({
            company: '连云港人文纪念园智慧陵园管理系统',
            dw: '连云港人文纪念园',
            sId: route.query.cm_mainid
        }).then(res => {

            familyData.value = res.data
            // familyData.value = [
            //     {
            //         cm_familyrow: "11",
            //         cm_fatherid: "",
            //         cm_id: "11",
            //         cm_kinship: "",
            //         cm_motherid: "",
            //         cm_name: "张一2",
            //         cm_seniorityrow: "11",
            //         cm_sex: "男",
            //         cm_spouseid: "11",
            //         name: "一老婆2",
            //         sex: "女"
            //     },
            //     {
            //         cm_familyrow: "1",
            //         cm_fatherid: "",
            //         cm_id: "1",
            //         cm_kinship: "",
            //         cm_motherid: "",
            //         cm_name: "张一",
            //         cm_seniorityrow: "1",
            //         cm_sex: "男",
            //         cm_spouseid: "1",
            //         name: "一老婆",
            //         sex: "女"
            //     },
                
            //     {
            //         cm_familyrow: "1",
            //         cm_fatherid: "1",
            //         cm_id: "2",
            //         cm_kinship: "",
            //         cm_motherid: "",
            //         cm_name: "张二",
            //         cm_seniorityrow: "1",
            //         cm_sex: "男",
            //         cm_spouseid: "2",
            //         name: "二老婆",
            //         sex: "女"
            //     },
            //     {
            //         cm_familyrow: "2",
            //         cm_fatherid: "1",
            //         cm_id: "111",
            //         cm_kinship: "",
            //         cm_motherid: "",
            //         cm_name: "张二2",
            //         cm_seniorityrow: "2",
            //         cm_sex: "男",
            //         cm_spouseid: "2",
            //         name: "二老婆2",
            //         sex: "女"
            //     },
            //     {
            //         cm_familyrow: "2",
            //         cm_fatherid: "2",
            //         cm_id: "3",
            //         cm_kinship: "",
            //         cm_motherid: "",
            //         cm_name: "张三2",
            //         cm_seniorityrow: "2",
            //         cm_sex: "男",
            //         cm_spouseid: "3",
            //         name: "三老婆2",
            //         sex: "女"
            //     },
            //     {
            //         cm_familyrow: "1",
            //         cm_fatherid: "2",
            //         cm_id: "4",
            //         cm_kinship: "",
            //         cm_motherid: "",
            //         cm_name: "张三1",
            //         cm_seniorityrow: "1",
            //         cm_sex: "男",
            //         cm_spouseid: "3",
            //         name: "三老婆1",
            //         sex: "女"
            //     },
            //     {
            //         cm_familyrow: "2",
            //         cm_fatherid: "4",
            //         cm_id: "5",
            //         cm_kinship: "",
            //         cm_motherid: "",
            //         cm_name: "张四2",
            //         cm_seniorityrow: "2",
            //         cm_sex: "男",
            //         cm_spouseid: "3",
            //         name: "四老婆2",
            //         sex: "女"
            //     },
            //     {
            //         cm_familyrow: "1",
            //         cm_fatherid: "4",
            //         cm_id: "6",
            //         cm_kinship: "",
            //         cm_motherid: "",
            //         cm_name: "张四1",
            //         cm_seniorityrow: "1",
            //         cm_sex: "男",
            //         cm_spouseid: "3",
            //         name: "四老婆1",
            //         sex: "女"
            //     }
            // ]
            fun([], true)
            let fi = 0
            familyArr1.value.forEach((el1, idx1) => {
                if (!familyArr2.value[fi]) {
                    // familyArr2.value[fi] = []
                    familyArr2.value.push([])
                }
                familyArr2.value[fi].push({
                    // title: idx1 + 1 + '世',
                    title: num.value[idx1] + '世'
                })

                if (fi == 0 && familyArr2.value[fi].length == 9) {
                    fi++
                } else if (familyArr2.value[fi].length == 10) {
                    fi++
                }
                el1.forEach((el2, idx2) => {
                    if (!familyArr2.value[fi]) {
                        // familyArr2.value[fi] = []
                        familyArr2.value.push([])
                    }
                    familyArr2.value[fi].push(el2)

                    if (fi == 0 && familyArr2.value[fi].length == 9) {
                        fi++
                    } else if (familyArr2.value[fi].length == 10) {
                        fi++
                    }
                })

            });
            console.log('familyArr2.value:')
            console.log(familyArr2.value)
        })
    })

    const fun = (arr1, isFirst = false) => {
        let arr2 = []
        if (isFirst) {
            //找出所有第一代，第一代只有一个，这里判断有多余
            familyData.value.forEach((item, index) => {
                if (!item.cm_fatherid) {
                    // if (arr2.length > 0) {
                    //     let _data = arr2[arr2.length - 1]
                    //     if (Number(arr2[arr2.length - 1].cm_familyrow) < Number(item.cm_familyrow)) {
                    //         arr2.push(item)
                    //     } else {
                    //         arr2[arr2.length - 1] = item
                    //         arr2.push(_data)
                    //     }
                    //
                    // } else {
                    //     arr2.push(item)
                    // }
                    arr2.push(item)
                }
            })
        } else {
            let sex = '男'
            arr1.forEach((item1, index1) => {
                familyData.value.forEach((item2, index2) => {
                    if (item2.cm_fatherid == item1.cm_id) {
                        item2.cm_sex == '男' ? sex = '子' : sex = '女'
                        // if (arr2.length > 0) {
                        //     let _data = arr2[arr2.length - 1]
                        //     if (Number(arr2[arr2.length - 1].cm_familyrow) < Number(item2.cm_familyrow)) {
                        //         arr2.push({call: item1.cm_name + ranking.value[Number(item2.cm_familyrow)-1] + sex, ...item2})
                        //     } else {
                        //         arr2[arr2.length - 1] = {call: item1.cm_name + ranking.value[Number(item2.cm_familyrow)-1] + sex, ...item2}
                        //         arr2.push(_data)
                        //     }
                        //
                        // } else {
                        //     arr2.push({call: item1.cm_name + ranking.value[Number(item2.cm_familyrow)-1] + sex, ...item2})
                        // }
                        // arr2.push({call: item1.cm_name + ranking.value[Number(item2.cm_familyrow)-1] + sex, ...item2})
                        arr2.push({fatherName: item1.cm_name, fatherFamilyrow: item1.cm_familyrow, ...item2})
                    }
                })
            })
        }
        //族谱根据排行排序，不管谁的后代只按排名
        console.log(arr2)
        for (let i = 0; i < arr2.length; i++) {
            for (let j = i + 1; j < arr2.length; j++) {
                console.log(arr2)
                if (Number(arr2[i].cm_familyrow) > Number(arr2[j].cm_familyrow)) {
                    let data = arr2[j]
                    arr2[j] = arr2[i]
                    arr2[i] = data
                    console.log(arr2)
                }
            }
        }
        //族谱再根据长辈排行排序
        let arr3 = []
        let fidArr1 = []
        for (let i = 0; i < arr2.length; i++) {
            // let row = arr2[i].fatherFamilyrow
            // let fid = arr2[i].cm_fatherid
            if(fidArr1.includes(arr2[i].cm_fatherid)) {
                continue
            } else {
                fidArr1.push(arr2[i].cm_fatherid)
                arr3.push(arr2[i])
            }
            for (let j = i + 1; j < arr2.length; j++) {
                if (arr2[j].cm_fatherid == arr2[i].cm_fatherid) {
                    arr3.push(arr2[j])
                }
            }
        }
        arr2 = JSON.parse(JSON.stringify(arr3))
        console.log(arr2)

        if (arr2.length > 0) {
            familyArr1.value.push(arr2)
            fun(arr2)
        } else {
            // 数据整理完加上配偶，还差简介
            let myarr = JSON.parse(JSON.stringify(familyArr1.value))
            // 循环判断长子长女给排名
            let fidArr = []
            for(let i = 0; i < myarr.length; i++) {
                for(let j = 0; j < myarr[i].length; j++) {
                    if (!myarr[i][j].cm_fatherid) {
                        continue
                    }
                    // 如果包含相同的父id则已经循环过不用再判断了
                    if(fidArr.includes(myarr[i][j].cm_fatherid)) {
                        continue
                    } else {
                        fidArr.push(myarr[i][j].cm_fatherid)
                    }
                    let manRank = 0
                    let womanRank = 0
                    if (myarr[i][j].cm_sex == '男') {
                        myarr[i][j].call = myarr[i][j].fatherName + ranking.value[manRank] + '子'
                        manRank++
                    } else if (myarr[i][j].cm_sex == '女') {
                        myarr[i][j].call = myarr[i][j].fatherName + ranking.value[womanRank] + '女'
                        womanRank++
                    }

                    for(let k = j + 1; k < myarr[i].length; k++) {
                        if (myarr[i][j].cm_fatherid != myarr[i][k].cm_fatherid) {
                            continue
                        } else {
                            if (myarr[i][k].cm_sex == '男') {
                                myarr[i][k].call = myarr[i][j].fatherName + ranking.value[manRank] + '子'
                                manRank++
                            } else if (myarr[i][k].cm_sex == '女') {
                                myarr[i][k].call = myarr[i][j].fatherName + ranking.value[womanRank] + '女'
                                womanRank++
                            }
                        }
                    }
                }
            }
            console.log(myarr)


            familyArr1.value.forEach((item1, index1) => {
                item1.forEach((item2, index2) => {
                    if (item2.name) {
                        myarr.forEach((item3, index3) => {
                            item3.forEach((item4, index4) => {
                                if (item4.cm_id == item2.cm_id) {
                                    console.log(item4)
                                    item3.splice(index4 + 1, 0, {
                                        cm_name: item4.name,
                                        call: '配偶',
                                        cm_synopsis: item4.synopsis
                                    })
                                }
                            })
                        })
                    }
                })
            })
            
            console.log(myarr)
            familyArr1.value = myarr
        }
    }
    const swipeChange = (idx) => {
        swipeIndex.value = idx
        console.log(swipeIndex.value)
    }
    const edit = () => {
        if (!(localStorage.getItem('jiapu_power') == 1 || localStorage.getItem('jiapu_power') == 2)) {
            //    没有权限
            showDialog({
                title: '提示',
                message: '您没有修改权限,请联系族长授权为管理员！'
            }).then(() => {
            });
            return false
        }
        if (familyArr2.value.length == 0) {
            router.push('/createFamilyTree?type=firstCreate&cm_mainid=' + route.query.cm_mainid)
        } else if (swipeIndex.value == 0 || swipeIndex.value == (familyArr2.value.length -1 + 2)) {
            if (!(localStorage.getItem('jiapu_power') == 1)) {
                //    没有权限
                showDialog({
                    title: '提示',
                    message: '您没有修改权限！'
                }).then(() => {
                });
                return false
            }
            router.push(`/createFamilyTree?type=editName&cm_mainid=${route.query.cm_mainid}&phone=${route.query.phone}`)
        } else {
            router.push('/relativeGraph?cm_mainid=' + route.query.cm_mainid)
        }
    }
    const del = () => {
        showConfirmDialog({
            title: '提示',
            message: '是否确定删除！'
        }).then(() => {
            if (!(localStorage.getItem('jiapu_power') == 1)) {
                //    没有权限
                showDialog({
                    title: '提示',
                    message: '您没有修改权限,请联系族长授权为管理员！'
                }).then(() => {
                });
                return false
            }
            showLoadingToast({
                message: '加载中...',
                overlay: true,
                forbidClick: true,
                duration: 0
            })
            delClanInfoApi({
                company: '连云港人文纪念园智慧陵园管理系统',
                dw: '连云港人文纪念园',
                sId: route.query.cm_mainid
            }).then(res => {
                closeToast()
                if (res.status == '+OK') {
                    router.push('/pedigreeOfAclan')
                } else {
                    showDialog({
                        title: '提示',
                        message: res.msg,
                    })
                }
            }).catch(err => {
                closeToast()
                showDialog({
                    title: '提示',
                    message: '网络异常，请稍后重试！',
                })
            })
        }).catch(() => {
        })
    }
</script>

<style lang='scss' scoped>
.home {
    width: 100vw;
    height: 100vh;
    // background: url('@/assets/bg/bg4.png');
    // background-size: 100% 100%;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    //backdrop-filter: blur(115px);
}
 .home::before {
     content: '';
     position: absolute;
     top: 0;
     right: 0;
     bottom: 0;
     left: 0;
     filter: blur(1px);
     background: url('@/assets/bg/bg6.png') no-repeat 100% 100%;
     background-size: cover;
     // opacity: .8;
     z-index: -1;
 }

.main {
    flex: 1;
    overflow: scroll;
    box-sizing: border-box;
    @include padding-global;
    background: rgba(255,255,255,0.9);
    display: flex;
    flex-direction: column;
    align-items: center;
}
.my-swipe {
    width: 100%;
    height: 500px;
    .swipe-item-1-text {
        position: absolute;
        top: 20px;
        width: 100%;
        text-align: center;
        z-index: 10;
        font-weight: bold;
    }
}
.box-1 {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    padding: 1px;
    border: 2px solid #000;
    .box-2 {
        width: 100%;
        height: 100%;
        box-sizing: border-box;
        border: 1px solid #000;
        display: flex;
        flex-direction: row-reverse;

        .box-3-header {
            width: 34px;
            writing-mode: vertical-rl;
            text-orientation:upright;
            letter-spacing: 10px;
            font-weight: bold;
            text-align: left;
            box-sizing: border-box;
            border-left: 1px solid #000;
            display: flex;
            align-items: center;
            background-color: #b7b7a2;
        }
        .box-3-title {
            width: 34px;
            writing-mode: vertical-rl;
            text-orientation:upright;
            font-weight: bold;
            text-align: left;
            display: flex;
            box-sizing: border-box;
            border-left: 1px solid #000;
            align-items: center;
            padding-top: 100px;
            background-color: #c9c9c0;
        }
        .box-4 {
            width: 34px;
            writing-mode: vertical-rl;
            text-orientation:upright;
            font-weight: bold;
            text-align: left;
            display: flex;
            box-sizing: border-box;
            border-left: 1px solid #000;
            background-color: rgb(226 233 233);
            .box-4-call {
                box-sizing: border-box;
                border-bottom: 1px solid #000;
                flex: 1;
                font-size: 10px;
                display: flex;
                justify-content: center;
                align-items: center;
            }
            .box-4-name {
                box-sizing: border-box;
                border-bottom: 1px solid #000;
                flex: 2;
                letter-spacing: 5px;
                display: flex;
                justify-content: center;
                align-items: center;
            }
            .box-4-direction {
                flex: 5;
                font-size: 10px;
            }
        }
    }
}
.mbutton {
    height: 50px;
    width: 100%;
    .mbutton-box {
        //width: 345px;
        width: 100%;
        position: fixed;
        bottom: 0;
        height: 50px;
        font-size: 17px;
        display: flex;
    }
}
</style>
